package com.librelato.tela.autorizacao;

import java.net.InetAddress;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.faces.application.NavigationHandler;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.servlet.http.HttpSession;

import com.librelato.bean.UsuarioBean;

public class AutorizaSessao implements PhaseListener {

	private static final long serialVersionUID = 5877802795737727089L;

	@Override
	public void afterPhase(PhaseEvent event) {
		FacesContext facesContext = event.getFacesContext();
		String currentPage = facesContext.getViewRoot().getViewId();

		String userAgent = facesContext.getExternalContext()
				.getRequestHeaderMap().get("User-Agent");
		Pattern pattern = Pattern.compile("Android");
		Matcher matcher = pattern.matcher(userAgent);
		String ip = null;
		boolean isLoginPage;
		if (matcher.find()) {
			isLoginPage = (currentPage.lastIndexOf("/indexmovel.xhtml") > -1);
		} else {
			isLoginPage = (currentPage.lastIndexOf("/index.xhtml") > -1);
		}

		HttpSession session = (HttpSession) facesContext.getExternalContext()
				.getSession(true);
		UsuarioBean usuario = (UsuarioBean) session.getAttribute("usuario");

		if (!isLoginPage && (usuario == null || usuario.getCodigo() == null)) {
			NavigationHandler nh = facesContext.getApplication()
					.getNavigationHandler();

			userAgent = facesContext.getExternalContext().getRequestHeaderMap()
					.get("User-Agent");
			pattern = Pattern.compile("Android");
			matcher = pattern.matcher(userAgent);

			if (matcher.find()) {
				nh.handleNavigation(facesContext, null, "/indexmovel.xhtml");
			} else {
				nh.handleNavigation(facesContext, null, "/index.xhtml");
			}

		}
	}

	@Override
	public void beforePhase(PhaseEvent event) {

	}

	@Override
	public PhaseId getPhaseId() {
		return PhaseId.RESTORE_VIEW;
	}

}
